define(
	["geom/polygon"],
	function(polygon) {
		function _latLongToPixel(val) {
			return val * 10000;
		}
	
		function _parseNode(ref, xml, nodes, offsetLat, offsetLon) {
			$(xml).find("#" + ref).each(function() {
				nodes.push(_latLongToPixel(+$(this).attr("lat") - offsetLat)); //x
				nodes.push(_latLongToPixel(+$(this).attr("lon") - offsetLon)); //z
			});
		}
			
		function _parseWay(full, xml, offsetLat, offsetLon) {		
			//Check for building tag
			if($(xml).find('tag[k="building"]').length <= 0)
				return null;
				
			//retval
			var retval = {
				verts	: [],
				indices : [],
				id		: $(xml).attr('id')
			};
			
			//Get base vertices
			var vertices = $(xml).find('nd');
			var verts = [];
			for(var i = 0; i < vertices.length - 1; ++i) {
				var vertex = vertices[i];
				_parseNode($(vertex).attr("ref"), full, verts, offsetLat, offsetLon);
			}
			
			//build base & roof vertices
			var n = verts.length;
			var height = 1;
			for(var i = 0; i < n; i += 2) {
				retval.verts.push(verts[i], 0, verts[i+1]);
			}
			for(var i = 0; i < n; i += 2) {
				retval.verts.push(verts[i], height, verts[i+1]);
			}
			
			//build wall indices
			n 	= verts.length/2;
			for(var i = 0; i < n; ++i) {
				retval.indices.push(
					i, i+n, (i+1)%n,
					i+n, ((i+1)%n)+n, (i+1)%n
				)
			}
			
			//roof
			var p = polygon.create();
			p.addVertices(verts);
			var idx = p.triangulate();
			for(var i = 0; idx != null && i < idx.length; ++i) {
				retval.indices.push(idx[i]+n);
			}
			
			return retval.indices ? retval : null;
		}
	
		return {
			parseOSM: function(xml) {
				var retval = [];
				
				//parse boundary
				var bounds = $(xml).find("bounds");
				offsetLat = bounds.attr("minlat");
				offsetLon = bounds.attr("minlon");
				console.log(offsetLat + "  :  " + offsetLon);
				
				$(xml).find('way').each(function(){
					var way = _parseWay(xml, this, offsetLat, offsetLon);
					if(way) retval.push(way);
				});
				return retval;
			}
		};
	}
);